const { db, query } = require("../../db/db");
const util = require("util");
const dayjs = require("dayjs");
const moment = require("moment");

async function PostChangeWelfareGoods(req, res) {
  const WelfareGoodsId = req.body.WelfareGoodsId;
  let UserId = Number(req.params.username);
  const WelfareHeightTypeCode = req.body.WelfareHeightTypeCode;
  console.log("详情", WelfareHeightTypeCode);

  if (WelfareHeightTypeCode !== "BuCrad") return;

  db.getConnection((err, connection) => {
    connection.beginTransaction(async (err) => {
      if (WelfareHeightTypeCode === "BuCrad") {
        //搜索价格,数量，可购买日期
        const Select_welfare_goods = util.format(
          "SELECT \
        DayResidueNum,\
        IFNULL(CanBuyTimeStart,'') as CanBuyTimeStart,\
        IFNULL(CanBuyTimeEnd,'') as CanBuyTimeEnd,\
        IFNULL(CurrentPrice,'') as CurrentPrice\
        FROM Welfare_Goods Where WelfareGoodsId=%s",
          WelfareGoodsId
        );
        connection.query(Select_welfare_goods, (err, result) => {
          if (err) {
            throw err;
          }
          if (result.length === 0)
            return res.send({
              status: 1,
              message: "商品不存在",
            });

          if (result[0].CanBuyTimeStart && result[0].CanBuyTimeEnd) {
            const StartTime = dayjs(result[0].CanBuyTimeStart);
            const endTime = dayjs(result[0].CanBuyTimeEnd);
            const timeToCheck = dayjs();
            const isBetween =
              timeToCheck.isAfter(StartTime) && timeToCheck.isBefore(endTime);
            if (!isBetween)
              return res.send({
                status: 1,
                message: "不在购买时间内",
              });
          }

          if (result[0].DayResidueNum === 0)
            return res.send({
              status: 1,
              message: "商品当日已售完",
            });

          //查看用户矿石数
          const Select_user_ore_num = util.format(
            "Select OreNum from User Where UserId=%s",
            UserId
          );
          connection.query(Select_user_ore_num, (err, resultUser) => {
            if (resultUser[0].OreNum < result[0].CurrentPrice) {
              return res.send({
                status: 1,
                message: "矿石不足",
              });
            }

            //购买成功,用户补卡数量+1,矿石数量-购买价格
            const UpdateOreNum = resultUser[0].OreNum - result[0].CurrentPrice;
            const Update_user_ore_num = util.format(
              "Update User Set BuCardNum=BuCardNum+1,OreNum=%s Where UserId=%s",
              UpdateOreNum,
              UserId
            );

            connection.query(Update_user_ore_num, (err, resultNum) => {
              //卡内容变更
              const Update_welfare_goods = util.format(
                "Update Welfare_Goods Set DayResidueNum=DayResidueNum-1,BuyPeopleNum=BuyPeopleNum+1 Where WelfareGoodsId=%s",
                WelfareGoodsId
              );
              connection.query(Update_welfare_goods, (err, resultUpldate) => {
                if (err) {
                  throw err;
                }

                connection.commit(function (err) {
                  if (err) {
                    connection.rollback(function () {
                      throw err;
                    });
                  }
                  res.send({
                    status: 0,
                  });
                  console.log("Transaction completed successfully.");
                });
              });
            });
          });
        });
      }
    });
  });
}

module.exports = { PostChangeWelfareGoods };
